package com.henry.base.concurrency.deadlock;

public class DeadLock2 implements Runnable {
    private Object lock1 = new Object();
    private Object lock2 = new Object();
    static volatile int a = 0;


    @Override
    public void run() {
        try {
            if (a == 0) {
                a++;
                synchronized (lock1) {
                    System.out.println(Thread.currentThread() + "get lock1");
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread() + "try get lock2");
                    synchronized (lock2) {
                        System.out.println(Thread.currentThread() + "get lock1 and lock2");
                    }
                }
            }else{
                a--;
                synchronized (lock2) {
                    System.out.println(Thread.currentThread() + "get lock2");
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread() + "try get lock1");
                    synchronized (lock1) {
                        System.out.println(Thread.currentThread() + "get lock1 and lock2");
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DeadLock2 deadLock2 = new DeadLock2();
        Thread t1 = new Thread(deadLock2);
        Thread t2 = new Thread(deadLock2);
        t1.start();
        t2.start();
        Thread.sleep(1000);
    }
}
